package com.linx.common.mybatis.helper;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.linx.common.core.constant.GlobalConstants;
import com.linx.common.core.utils.SpringUtils;
import com.linx.common.core.utils.StringUtils;
import com.linx.common.core.utils.reflect.ReflectUtils;
import com.linx.common.redis.utils.RedisUtils;
import com.linx.common.satoken.utils.LoginHelper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 租户助手
 *
 * @author Lion Li
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ParkHelper {

    private static final String DYNAMIC_PARK_KEY = GlobalConstants.GLOBAL_REDIS_KEY + "dynamicPark";

    private static final ThreadLocal<String> TEMP_DYNAMIC_PARK = new ThreadLocal<>();

    private static final ThreadLocal<Stack<Integer>> REENTRANT_IGNORE = ThreadLocal.withInitial(Stack::new);

    /**
     * 租户功能是否启用
     */
    public static boolean isEnable() {
        return Convert.toBool(SpringUtils.getProperty("tenant.enable"), false);
    }

    private static IgnoreStrategy getIgnoreStrategy() {
        Object ignoreStrategyLocal = ReflectUtils.getStaticFieldValue(ReflectUtils.getField(InterceptorIgnoreHelper.class, "IGNORE_STRATEGY_LOCAL"));
        if (ignoreStrategyLocal instanceof ThreadLocal<?> IGNORE_STRATEGY_LOCAL) {
            if (IGNORE_STRATEGY_LOCAL.get() instanceof IgnoreStrategy ignoreStrategy) {
                return ignoreStrategy;
            }
        }
        return null;
    }

    /**
     * 开启忽略租户(开启后需手动调用 {@link #disableIgnore()} 关闭)
     */
    public static void enableIgnore() {
        IgnoreStrategy ignoreStrategy = getIgnoreStrategy();
        if (ObjectUtil.isNull(ignoreStrategy)) {
            InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().tenantLine(true).build());
        } else {
            ignoreStrategy.setTenantLine(true);
        }
        Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
        reentrantStack.push(reentrantStack.size() + 1);
    }

    /**
     * 关闭忽略租户
     */
    public static void disableIgnore() {
        IgnoreStrategy ignoreStrategy = getIgnoreStrategy();
        if (ObjectUtil.isNotNull(ignoreStrategy)) {
            boolean noOtherIgnoreStrategy = !Boolean.TRUE.equals(ignoreStrategy.getDynamicTableName())
                && !Boolean.TRUE.equals(ignoreStrategy.getBlockAttack())
                && !Boolean.TRUE.equals(ignoreStrategy.getIllegalSql())
                && !Boolean.TRUE.equals(ignoreStrategy.getDataPermission())
                && CollectionUtil.isEmpty(ignoreStrategy.getOthers());
            Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
            boolean empty = reentrantStack.isEmpty() || reentrantStack.pop() == 1;
            if (noOtherIgnoreStrategy && empty) {
                InterceptorIgnoreHelper.clearIgnoreStrategy();
            } else if (empty) {
                ignoreStrategy.setTenantLine(false);
            }
        }
    }

    /**
     * 在忽略租户中执行
     *
     * @param handle 处理执行方法
     */
    public static void ignore(Runnable handle) {
        enableIgnore();
        try {
            handle.run();
        } finally {
            disableIgnore();
        }
    }

    /**
     * 在忽略租户中执行
     *
     * @param handle 处理执行方法
     */
    public static <T> T ignore(Supplier<T> handle) {
        enableIgnore();
        try {
            return handle.get();
        } finally {
            disableIgnore();
        }
    }

    public static void setDynamic(String parkInfoId) {
        setDynamic(parkInfoId, false);
    }

    /**
     * 设置动态租户(一直有效 需要手动清理)
     * <p>
     * 如果为未登录状态下 那么只在当前线程内生效
     *
     * @param parkInfoId 租户id
     * @param global   是否全局生效
     */
    public static void setDynamic(String parkInfoId, boolean global) {
        if (!isEnable()) {
            return;
        }
        if (!isLogin() || !global) {
            TEMP_DYNAMIC_PARK.set(parkInfoId);
            return;
        }
        String cacheKey = DYNAMIC_PARK_KEY + ":" + LoginHelper.getUserId();
        RedisUtils.setCacheObject(cacheKey, parkInfoId);
        //设置loginUser缓存
        LoginHelper.getLoginUser().setParkInfoIdDynamic(Long.valueOf(parkInfoId));

    }

    /**
     * 获取动态租户(一直有效 需要手动清理)
     * <p>
     * 如果为未登录状态下 那么只在当前线程内生效
     */
    public static String getDynamic() {
        if (!isEnable()) {
            return null;
        }
        if (!isLogin()) {
            return TEMP_DYNAMIC_PARK.get();
        }
        // 如果线程内有值 优先返回
        String parkInfoId = TEMP_DYNAMIC_PARK.get();
        if (StringUtils.isNotBlank(parkInfoId)) {
            return parkInfoId;
        }
        String cacheKey = DYNAMIC_PARK_KEY + ":" + LoginHelper.getUserId();
        parkInfoId = RedisUtils.getCacheObject(cacheKey);
        return parkInfoId;
    }

    /**
     * 清除动态租户
     */
    public static void clearDynamic() {
        if (!isEnable()) {
            return;
        }
        if (!isLogin()) {
            TEMP_DYNAMIC_PARK.remove();
            return;
        }
        TEMP_DYNAMIC_PARK.remove();
        String cacheKey = DYNAMIC_PARK_KEY + ":" + LoginHelper.getUserId();
        RedisUtils.deleteObject(cacheKey);
    }

    /**
     * 在动态租户中执行
     *
     * @param handle 处理执行方法
     */
    public static void dynamic(String parkInfoId, Runnable handle) {
        setDynamic(parkInfoId);
        try {
            handle.run();
        } finally {
            clearDynamic();
        }
    }

    /**
     * 在动态租户中执行
     *
     * @param handle 处理执行方法
     */
    public static <T> T dynamic(String parkInfoId, Supplier<T> handle) {
        setDynamic(parkInfoId);
        try {
            return handle.get();
        } finally {
            clearDynamic();
        }
    }

    /**
     * 获取当前租户id(动态租户优先)
     */
    public static String getparkInfoId() {
        if (!isEnable()) {
            return null;
        }
        String parkInfoId = ParkHelper.getDynamic();
        if (StringUtils.isBlank(parkInfoId)) {
            parkInfoId = LoginHelper.getParkInfoId();
            if(StringUtils.isNotBlank(parkInfoId)){
                boolean hasComma = parkInfoId.indexOf(",") != -1;
                if(hasComma){
                    List<Long> list = Arrays.stream(parkInfoId.split(","))
                        .map(Long::parseLong)
                        .collect(Collectors.toList());

                    parkInfoId= String.valueOf(list.get(0));
                    ParkHelper.setDynamic(parkInfoId, true);
                }
            }

        }
        return parkInfoId;
    }

    private static boolean isLogin() {
        try {
            StpUtil.checkLogin();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
